package com.glance.browser.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.glance.browser.domain.User;
import com.glance.browser.repository.UserRepository;

@Repository
@Transactional(readOnly = true)
public class UserDAOImpl implements UserDAO {

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private UserRepository repository;

	public User findByUsername (String username) {
		return repository.findByUsername(username);
	}

	public List<User> findAll() {
		return repository.findAll();
	}

	public List<User> findAll(int page, int pageSize) {

		TypedQuery<User> query = entityManager.createQuery("select u from User u", User.class);

		query.setFirstResult(page * pageSize);
		query.setMaxResults(pageSize);

		return query.getResultList();
	}
	
	public long count(){
		return repository.count();
	}
	
	public boolean exists(String username){
		return repository.exists(username);
	}

	@Transactional
	public User save(User user) {
		return repository.save(user);
	}
	
	@Transactional
	public void delete(String username){
		repository.delete(username);
	}
	
	@Transactional
	public void deleteAll(){
		repository.deleteAll();
	}
	
	@Transactional
	public void deleteAllExcept(String username){
		repository.deleteAllExcept(username);
	}

	public boolean authenticate(String username, String password) {
		if (repository.findByUsernameAndPassword(username, password) != null)
			return true;
		else
			return false;
	}

}
